package com.ligongmusic.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class LrcUtil {

	private static final char[] miarry = { '@', 'G', 'a', 'w', '^', '2', 't',
			'G', 'Q', '6', '1', '-', 'Î', 'Ò', 'n', 'i' };
	/**
	 * 从assets目录下读取歌词文件内容
	 */
	public static String getFromAssets(String filePath) {
		if (filePath.endsWith(".krc")){
			try{
				// 酷狗音乐歌词文件
				File krcfile = new File(filePath);
				byte[] zip_byte = new byte[(int) krcfile.length()];
				FileInputStream fileinstrm = new FileInputStream(krcfile);
				byte[] top = new byte[4];
				fileinstrm.read(top);
				fileinstrm.read(zip_byte);
				int j = zip_byte.length;
				if (j == 0){
					return null;
				}
				for (int k = 0; k < j; k++)
				{
					int l = k % 16;
					int tmp67_65 = k;
					byte[] tmp67_64 = zip_byte;
					tmp67_64[tmp67_65] = (byte) (tmp67_64[tmp67_65] ^ miarry[l]);
				}
				String krc_text = new String(decompress(zip_byte), "utf-8");
				krc_text = krc_text.replaceAll("<.*?>", "").replaceAll("\\[language(.*?)\\]", "").replaceAll("\\[hash(.*?)\\]", "");
				krc_text = extractMessageByRegular(krc_text);
//				LoggerUtils.getLog(LrcUtil.class).error(krc_text);
				return krc_text;
			}catch (Exception e){
				return null;
			}
		}
		try {
			File file = new File(filePath);
			InputStream is = new FileInputStream(file);
			InputStreamReader inputReader = new InputStreamReader(is, "gbk");
			BufferedReader bufReader = new BufferedReader(inputReader);
			String line = "";
			String result = "";
			while ((line = bufReader.readLine()) != null) {
				if (line.trim().equals(""))
					continue;
				result += line + "\r\n";
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 使用正则表达式提取中括号中的内容
	 * @param msg
	 * @return
	 */
	public static String extractMessageByRegular(String msg){
		Pattern p = Pattern.compile("(\\[[^\\]]*\\])");
		Matcher m = p.matcher(msg);
		while(m.find()){
			String str = m.group().substring(1, m.group().length()-1);
			try{
				String[] split = str.split(",");
				String spl = "";
//				for(int i = 0; i < split.length; i++){
					spl += "[" + ms2Date(Long.parseLong(split[0])) + "]";
//				}
				msg = msg.replace(m.group(), spl);
			}catch (Exception e) {
				continue;
			}
		}
		return msg;
	}

	public static String ms2Date(long ms){
		DateFormat formatter = new SimpleDateFormat("mm:ss.SS");
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(ms);
		return formatter.format(calendar.getTime());
	}

//	public static byte[] compress(byte[] data) {
//		byte[] output = new byte[0];
//		Deflater compresser = new Deflater();
//		compresser.reset();
//		compresser.setInput(data);
//		compresser.finish();
//		ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
//		try {
//			byte[] buf = new byte[1024];
//			while (!compresser.finished()) {
//				int i = compresser.deflate(buf);
//				bos.write(buf, 0, i);
//			}
//			output = bos.toByteArray();
//		} catch (Exception e) {
//			output = data;
//			e.printStackTrace();
//		} finally {
//			try {
//				bos.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		compresser.end();
//		return output;
//	}

//	public static void compress(byte[] data, OutputStream os) {
//		DeflaterOutputStream dos = new DeflaterOutputStream(os);
//		try {
//			dos.write(data, 0, data.length);
//			dos.finish();
//			dos.flush();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	public static byte[] decompress(byte[] data) {
		byte[] output = new byte[0];
		Inflater decompresser = new Inflater();
		decompresser.reset();
		decompresser.setInput(data);
		ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
		try {
			byte[] buf = new byte[1024];
			while (!decompresser.finished()) {
				int i = decompresser.inflate(buf);
				o.write(buf, 0, i);
			}
			output = o.toByteArray();
		} catch (Exception e) {
			output = data;
			e.printStackTrace();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		decompresser.end();
		return output;
	}

//	public static byte[] decompress(InputStream is) {
//		InflaterInputStream iis = new InflaterInputStream(is);
//		ByteArrayOutputStream o = new ByteArrayOutputStream(1024);
//		try {
//			int i = 1024;
//			byte[] buf = new byte[i];
//			while ((i = iis.read(buf, 0, i)) > 0) {
//				o.write(buf, 0, i);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return o.toByteArray();
//	}
}
